//
//  NSString+Json.m
//  CoderSahara
//
//  Created by CoderSahara on 2020/6/15.
//  Copyright © 2020 CoderSahara. All rights reserved.
//

#import "NSString+Json.h"

@implementation NSString (Json)

#pragma mark - JSON 字符串转换
/*
 
 * @brief 把格式化的JSON格式的字符串转换成字典
 
 * @param jsonString JSON格式的字符串
 
 * @return 返回字典
 
 */

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                         
                                                        options:NSJSONReadingMutableContainers
                         
                                                          error:&err];
    if(err) {
        
        NSLog(@"json解析失败：%@",err);
        
        return nil;
        
    }
    return dic;
}

+ (NSArray *)arrayWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData
                         
                                                        options:NSJSONReadingMutableContainers
                         
                                                          error:&err];
    if(err) {
        
        NSLog(@"json解析失败：%@",err);
        
        return nil;
        
    }
    return arr;
}


// 字典转JSON
+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    
    if (!dic) {
        return @"";
    }
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

//时间戳变为格式时间
+ (NSString *)timeStrToTime:(NSString *)timeStr
{

//    如果服务器返回的是13位字符串，需要除以1000，否则显示不正确(13位其实代表的是毫秒，需要除以1000)
    long long time=[timeStr longLongValue] / 1000;

    NSDate *date = [[NSDate alloc]initWithTimeIntervalSince1970:time];

    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];

    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSString*timeString=[formatter stringFromDate:date];

    return timeString;

}
// 下载速度转换
- (NSString *)loadSpeedWithBitForSec{
    NSInteger speed = self.integerValue;
    NSString *speedStr;
    if (speed >= 0 && speed/1024 < 1) {
        speedStr = [NSString stringWithFormat:@"%.2lfB/s",(double)speed];
    }
    else if(speed/1024 >= 1 && speed/1024 <= 999 ) {
        speedStr = [NSString stringWithFormat:@"%.2lfKB/s",speed/1024.f];
    }else if(speed/1024 > 999 ){
        speedStr = [NSString stringWithFormat:@"%.2lfMB/s",speed/1024/1024.f];
    }
    return speedStr;
}

@end
